/*
 * @Description:
 * @Author: maxyang
 * @Date: 2022-06-20 10:37:33
 * @LastEditTime: 2022-07-14 22:38:52
 * @LastEditors: liutq
 * @Reference:
 */
package common

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/maxyang107/jinglan/model"
	"github.com/maxyang107/jinglan/model/system"
	"github.com/maxyang107/jinglan/notice"
)

type Token struct {
	AccessToken string `json:"access_token"`
	ExpireIn    uint   `json:"expire_in"`
}

type Status struct {
	StatusCode   int8   `json:"status_code"`
	StatusReason string `json:"status_reason"`
}

type Resp struct {
	RespResult Token `json:"result"`

	RespStatus Status `json:"status"`
}

type VGoods struct {
	Price    string   `json:"price"`
	Stock    int      `json:"stock"`
	Imgs     []string `json:"imgs"`
	ItemName string   `json:"item_name"`
	Itemid   string   `json:"itemid"`
	Url      string   `json:"url"`
}

type Vresult struct {
	Items    []VGoods `json:"items"`
	ItemNum  int      `json:"item_num"`
	TotalNum int      `json:"total_num"`
}

type VShopgoods struct {
	Result Vresult `json:"result"`
}

/**
 * @description: 方法描述：获取token
 * @Author: maxyang
 * @return {*}
 */
func GetAccessToken() (string, error) {
	vtoken := model.GetKey("vshoptoken-new")

	if vtoken != "" {
		return vtoken, nil
	}
	var resp_ Resp
	resp, err := http.Get("https://oauth.open.weidian.com/token?grant_type=client_credential&appkey=3703030101&secret=e08bae23fe96e969eff6094c2ef901c4")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return "", err
	}

	err2 := json.Unmarshal(body, &resp_)
	fmt.Println(resp_.RespResult.AccessToken)

	if err2 != nil {
		return "", err
	}

	if resp_.RespStatus.StatusCode != 0 {
		return "", err
	}

	model.SetKey("vshoptoken-new", resp_.RespResult.AccessToken, time.Duration(resp_.RespResult.ExpireIn-1000))
	return resp_.RespResult.AccessToken, nil
}

/**
 * @description: 方法描述：获取订单列表
 * @Author: maxyang
 * @return {*}
 */
func GetVOrderList() (*VResp, error) {
	var resp_ VResp

	token, err := GetAccessToken()

	if err != nil {
		return nil, err
	}

	public := map[string]string{"method": "vdian.order.list.get", "access_token": token, "version": "1.2"}

	param := map[string]interface{}{"page_num": 1, "page_size": 20, "order_type": "shiped"}

	json_public, err := json.Marshal(public)

	if err != nil {

		return nil, err

	}

	json_param, err := json.Marshal(param)

	if err != nil {

		return nil, err

	}

	resp, err := http.Post(fmt.Sprintf("https://api.vdian.com/api?param=%s&public=%s", json_param, json_public), "application/json", bytes.NewBuffer(nil))

	if err != nil {
		return nil, err
	}

	json.NewDecoder(resp.Body).Decode(&resp_)
	return &resp_, nil
}

/**
 * @description: 方法描述：获取订单信息
 * @Author: maxyang
 * @return {*}
 * @param {string} orderId
 * @param {string} token
 */
func GetSubOrderInfo(orderId string, token string) (*SubResult, error) {
	var subresp SubResult

	public := map[string]string{"method": "vdian.order.get", "access_token": token, "version": "1.0", "format": "json"}

	param := map[string]interface{}{"order_id": orderId}

	json_public, err := json.Marshal(public)

	if err != nil {

		return nil, err

	}

	json_param, err := json.Marshal(param)

	if err != nil {

		return nil, err
	}
	resp, err := http.Post(fmt.Sprintf("https://api.vdian.com/api?param=%s&public=%s", json_param, json_public), "application/json", bytes.NewBuffer(nil))

	if err != nil {

		return nil, err

	}

	json.NewDecoder(resp.Body).Decode(&subresp)

	return &subresp, nil

}

/**
 * @description: 方法描述：退款
 * @Author: maxyang
 * @return {*}
 * @param {string} orderid
 */
func Refound(orderid string) error {

	token, err := GetAccessToken()

	if err != nil {
		return err
	}

	suborderinfo, err := GetSubOrderInfo(orderid, token)
	if err != nil {
		return err
	}

	var subOrderId []int

	for _, v := range suborderinfo.Result.Items {
		subOrderId = append(subOrderId, v.SubOrderId)
	}

	param := map[string]interface{}{"refundType": 1, "reasonId": 3, "refundReason": "其他原因", "refundDesc": "不符合购买条件", "orderId": orderid, "refundItemFee": suborderinfo.Result.Total, "refundExpressFee": "0.00", "refundIntegral": 0, "refundVoucher": "", "source": 2, "refundSubOrderIdList": subOrderId, "refundItemNum": 1, "refundFirstStageFee": "", "refundSecondStageFee": ""}

	json_param, err := json.Marshal(param)

	if err != nil {

		return err
	}

	client := &http.Client{}
	req, err := http.NewRequest("POST", fmt.Sprintf("https://thor.weidian.com/refundplatform/onSale.sellerCreateRefund/1.0?param=%s&wdtoken=5b6a4bb5&_=1655718309492", json_param), nil)
	q := req.URL.Query()
	q.Add("param", string(json_param))
	req.URL.RawQuery = q.Encode()
	if err != nil {
		return err
	}
	sc := system.GetSysConfigDetail(Cookie)
	req.Header.Add("cookie", sc.ConfigValue)
	req.Header.Add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36")
	req.Header.Add("Content-Type", "application/json;charset=utf-8")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err.Error())
	}
	defer resp.Body.Close()
	var res_ VRefoundResult
	json.NewDecoder(resp.Body).Decode(&res_)
	if res_.StatusInfo.StatusCode == 2 {
		notice.NoticeDingTalk("登录失效，请尽快重置cookie！", "https://www.baidu.com")
		return errors.New("cookie过期")
	}

	if res_.StatusInfo.StatusCode != 0 {
		notice.NoticeDingTalk(res_.StatusInfo.StatusReason, "")
		log.Fatalln(res_.StatusInfo)
		return errors.New("退款失败")
	}
	return nil
}

/**
 * @description: 方法描述：拉取微店商品
 * @Author: maxyang
 * @return {*}
 */
func GetVshopGoodsList(page_num int, page_size int) (*VShopgoods, error) {

	token, err := GetAccessToken()

	if err != nil {
		fmt.Println(err.Error())
	}
	public := map[string]string{"method": "vdian.item.list.get", "access_token": token, "version": "1.1", "format": "json"}

	param := map[string]interface{}{"page_size": fmt.Sprintf("%d", page_size), "status": 4, "orderby": "1", "page_num": fmt.Sprintf("%d", page_num)}

	json_public, err := json.Marshal(public)

	if err != nil {

		return nil, err
	}

	json_param, err := json.Marshal(param)

	if err != nil {

		return nil, err
	}
	fmt.Println(fmt.Sprintf("https://api.vdian.com/api?param=%s&public=%s", json_param, json_public))
	resp, err := http.Post(fmt.Sprintf("https://api.vdian.com/api?param=%s&public=%s", json_param, json_public), "application/json", bytes.NewBuffer(nil))
	if err != nil {
		return nil, err
	}
	var resp_ VShopgoods
	json.NewDecoder(resp.Body).Decode(&resp_)
	for k, v := range resp_.Result.Items {
		resp_.Result.Items[k].Url = fmt.Sprintf("https://weidian.com/fastorder.html?itemID=%s", v.Itemid)
	}
	return &resp_, nil
}
